import React, {Component, FormEvent} from 'react';
import PropTypes from 'prop-types';
import './ImgSlice.scss'
import {readBlobAsDataURL, setData} from "@/shared";


class ImgSlice extends Component {
    static propTypes: {};
    canvasRef!: HTMLCanvasElement;
    state: any = {
        imgSrc: ""
    }
    ImgDom!: HTMLImageElement;

    DrawImg() {
        let {canvasRef} = this;
        var ctx = canvasRef?.getContext('2d');
        // img,sx,sy,swidth,sheight,x,y,width,height)
        // 前两位控制 要截取图片的位置 左上角为起点 3，4 和最后两位建议相同
        ctx?.drawImage(this.ImgDom, 0,0,100,100,0,0,100,100)
    }

    async changeImg(e: FormEvent<HTMLInputElement>) {
        e.persist();
        let file = e.currentTarget.files ? e.currentTarget.files[0] : new File(["First Line Text", "Second Line Text"], '123');
        let res = await readBlobAsDataURL(file) as any;
        let data = {
            imgSrc: res.currentTarget.result
        }
        await setData.call(this, data);

    }

    render() {
        let {imgSrc} = this.state;
        return (
            <div>
                <input type="file" onInput={(e: FormEvent<HTMLInputElement>) => {
                    this.changeImg(e)
                }}/>
                <div className={'slice-img'}>
                    <img src={imgSrc} alt="" ref={(ref: HTMLImageElement) => {
                        this.ImgDom = ref
                    }}/>
                    <div className="slice-kuang">
                    </div>
                </div>
                <canvas width="100" height="100" ref={(ref: HTMLCanvasElement) => this.canvasRef = ref}></canvas>
                <button onClick={()=>this.DrawImg()} >印刷</button>
            </div>
        );
    }
}

ImgSlice.propTypes = {};

export default ImgSlice;